#include "mywidget.h"
#include "ui_mywidget.h"
#include <QPushButton>
#include <QFileDialog>
#include <QKeyEvent>
#include <QMimeData>
#include <QFile>
#include <QTimer>
#include <QRegularExpressionMatch>
#include <QProcess>
#include <QFileDialog>
#include <QDebug>





MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyWidget)
{
    ui->setupUi(this);
    this->setAcceptDrops(true); //接收拖拽文件
    setWindowFlags(Qt::FramelessWindowHint);//隐藏标题栏
    //捕获事件过滤器
    ui->labelTitle->installEventFilter(this);
    ui->titleBar->installEventFilter(this);
    ui->label_help->installEventFilter(this);
    ui->label_close->installEventFilter(this);
    ui->label_jz->installEventFilter(this);
    //设置捐助图片
    QPixmap pixmapWxzf(":/pic/wx.png");
    QPixmap pixmapZfbzf(":/pic/zfb.png");
    ui->label_wxzf->setPixmap(pixmapWxzf);
    ui->label_wxzf->show();
    ui->label_zfbzf->setPixmap(pixmapZfbzf);
    ui->label_zfbzf->show();
    ui->label_wxzf->setVisible(false);
    ui->label_zfbzf->setVisible(false);

//libpng warning: iCCP: known incorrect sRGB profile 因为某些png图片出现警告,下面处理一次图片即可
//    QImage img;
//    img.load("D:/War3Tools/ClearMap/pic/checked.png");
//    img.save("D:/War3Tools/ClearMap/pic/checked.png");
//    img.load("D:/War3Tools/ClearMap/pic/unchecked.png");
//    img.save("D:/War3Tools/ClearMap/pic/unchecked.png");
//    img.load("D:/War3Tools/ClearMap/pic/chongzhi.png");
//    img.save("D:/War3Tools/ClearMap/pic/chongzhi.png");
//    img.load("D:/War3Tools/ClearMap/pic/close.png");
//    img.save("D:/War3Tools/ClearMap/pic/close.png");
//    img.load("D:/War3Tools/ClearMap/pic/help.png");
//    img.save("D:/War3Tools/ClearMap/pic/help.png");
//    img.load("D:/War3Tools/ClearMap/pic/chongzhi_choose.png");
//    img.save("D:/War3Tools/ClearMap/pic/chongzhi_choose.png");
//    img.load("D:/War3Tools/ClearMap/pic/close_choose.png");
//    img.save("D:/War3Tools/ClearMap/pic/close_choose.png");
//    img.load("D:/War3Tools/ClearMap/pic/help_choose.png");
//    img.save("D:/War3Tools/ClearMap/pic/help_choose.png");
//    img.load("D:/War3Tools/ClearMap/pic/wx.png");
//    img.save("D:/War3Tools/ClearMap/pic/wx.png");
//    img.load("D:/War3Tools/ClearMap/pic/zfb.png");
//    img.save("D:/War3Tools/ClearMap/pic/zfb.png");
    //初始隐藏控件
    showFirstUI(true);
    //读取w3x2lni的路径
    QString CleanMapExePath = QCoreApplication::applicationDirPath();
    QFile configIni(CleanMapExePath+"/CleanMapConfig.ini");
    if(configIni.open(QIODevice::ReadOnly))
    {
        m_w2lPath = configIni.readLine();
        configIni.close();
    }

    //指定默认白名单文件
    m_whiteListFile = CleanMapExePath +"/whiteList.ini";
    qDebug() << "白名单文件:" << m_whiteListFile;
    //工作线程
    worker->moveToThread(&workerThread);
    connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
    connect(this,&MyWidget::sign_starWorkThread, worker, &WorkThread::SearchFile);
    connect(worker, &WorkThread::sign_responseFileCount, this, &MyWidget::sl_responseCount);
    connect(worker, &WorkThread::sign_responseExeLog, this, &MyWidget::sl_responseExeLog);
    connect(worker, &WorkThread::sign_workOver, this, &MyWidget::sl_workOver);

    workerThread.start();
    setInfo();

    //计时器
    m_timer = new QTimer(this);
    connect(m_timer,&QTimer::timeout,[=](){m_costTime += 0.01;});

    connect(ui->Btn_Start,&QPushButton::clicked,[=](){
        if(m_war3MapFile.isEmpty())return ;
        if(m_w2lPath.isEmpty()) return ;
        if(m_isWorkOver == 2) return ;//程序已执行.
        m_isWorkOver = 2;
//        emit sign_starWorkThread(m_war3MapFile,m_w2lPath,m_WhiteListMdxFile,m_WhiteListPicFile,m_read_slk);
        emit sign_starWorkThread(m_war3MapFile,m_w2lPath,m_whiteListFile,m_read_slk,m_del_lni);
        m_timer->start(10);
    });
}



MyWidget::~MyWidget()
{
    delete ui;
    workerThread.quit();
    workerThread.wait();
    qDeleteAll(itemList.begin(), itemList.end());
    itemList.clear();
    qDeleteAll(headerList.begin(), headerList.end());
    headerList.clear();
}
bool MyWidget::eventFilter(QObject * watched, QEvent * event)
{
    if (watched == ui->titleBar && event->type() == QEvent::MouseButtonPress) m_bDrag = true;
    if (watched == ui->titleBar && event->type() == QEvent::MouseButtonRelease) m_bDrag = false;

    if (watched == ui->label_help && event->type() == QEvent::MouseButtonPress) label_help_clicked();
    if (watched == ui->label_close && event->type() == QEvent::MouseButtonPress) this->close();
    if (watched == ui->label_jz && event->type() == QEvent::MouseButtonPress)
    {
        showFirstUI(false);
        ui->label_wxzf->setVisible(true);
        ui->label_zfbzf->setVisible(true);
        ui->btnReturn->setVisible(true);
    }
    return QWidget::eventFilter(watched, event);
}

void MyWidget::sl_responseCount(int all,int script,int mdx,int pic,int usedMdx,int usedPic,
                                int delMdx,int delPic)
{
    m_allFileCount = all;
    m_scriptFileCount = script;
    m_mdxFileCount = mdx;
    m_picFileCount = pic;
    m_usedMdxFileCount = usedMdx;
    m_usedPicFileCount = usedPic;
    m_delMdxFileCount = delMdx;
    m_delPicFileCount = delPic;
    setInfo();
}
void MyWidget::sl_workOver(int overCode)
{
    switch (overCode)
    {
        case 1:
            ui->label_info->setText("转换为Lni格式地图失败...");
            break;
        case 2:
            ui->label_info->setText("转换为Lni格式地图失败...");
            break;
        default:
            ui->label_info->setText("执行完毕!用时:"+QString().setNum(m_costTime)+"秒");
    }
    m_isWorkOver = 1;
    m_timer->stop();
    m_costTime = 0;

}
void MyWidget::sl_responseExeLog(QString str)
{
    ui->label_info->setText(str);
}


void MyWidget::dragEnterEvent(QDragEnterEvent *event)
{
    // 判断拖拽文件类型，文件名 接收该动作
    if (event->mimeData()->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}

// 拖拽释放处理函数
void MyWidget::dropEvent(QDropEvent *event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    if (urls.isEmpty()) return;

    QString fileName = urls.first().toLocalFile();
    if (fileName.isEmpty()) return;
    QString CleanMapExePath = QCoreApplication::applicationDirPath();

    if(fileName.contains(QRegExp(".*w2l\\.exe")))
    {
        //读取配置文件中的目录
        QFile configIni(CleanMapExePath+"/CleanMapConfig.ini");
        if(!configIni.open(QIODevice::WriteOnly))
        {
            ui->textBrowser->setText("打开配置文件失败,可能是硬盘存储空间不足.");
            return;
        }
        m_w2lPath = fileName;
        configIni.write(fileName.toUtf8());
        configIni.close();
        setInfo();
    }

    if(fileName.contains(QRegExp(".*\\.ini")))
    {
        m_whiteListFile = fileName;
        setInfo();
    }


    if(fileName.contains(QRegExp(".*\\.w3x")))
    {
        ui->labelDir->setText(fileName);
        m_war3MapFile = fileName;
        m_allFileCount = 0;
        m_mdxFileCount = 0;
        m_picFileCount = 0;
        m_usedMdxFileCount = 0;
        m_usedPicFileCount = 0;
        m_delMdxFileCount = 0;
        m_delPicFileCount = 0;;
        setInfo();
        ui->label_info->setText("");
    }

}


//移动窗口
void MyWidget::mousePressEvent(QMouseEvent *event)
{
    if (!m_bDrag) return;
    if(event->button() == Qt::LeftButton)
    {
        //获得鼠标的初始位置
        m_mouseStartPoint = event->globalPos();
        //获得窗口的初始位置
        m_windowTopLeftPoint = this->frameGeometry().topLeft();
    }
}

void MyWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_bDrag) return;

    if(event->buttons() & Qt::LeftButton)
    {
        //获得鼠标移动的距离
        QPoint distance = event->globalPos() - m_mouseStartPoint;
        //改变窗口的位置
        this->move(m_windowTopLeftPoint + distance);
    }
}


void MyWidget::setInfo()
{
m_info =
QString("\
w2l: %1 \n\
地图: %2 \n\
白名单文件: %3 \n\
").arg(m_w2lPath).arg(m_war3MapFile).arg(m_whiteListFile)
+QString("\n\
文件数量: %1\n\
模型文件: %2\n\
贴图文件: %3\n\
使用模型文件: %4\n\
使用贴图文件: %5\n\
删除模型文件: %6\n\
删除贴图文件: %7\n\
")
.arg(QString().setNum(m_allFileCount))
.arg(QString().setNum(m_mdxFileCount))
.arg(QString().setNum(m_picFileCount))
.arg(QString().setNum(m_usedMdxFileCount))
.arg(QString().setNum(m_usedPicFileCount))
.arg(QString().setNum(m_delMdxFileCount))
.arg(QString().setNum(m_delPicFileCount));


    ui->textBrowser->setText(m_info);
    if(m_w2lPath.isEmpty())
    {
       ui->textBrowser->append(TEXT_COLOR_RED("请将w3x2lni目录下的w2l.exe拖进来."));
    }
    if(m_war3MapFile.isEmpty())
    {
       ui->textBrowser->append(TEXT_COLOR_RED("请将地图拖进来."));
    }
}


void MyWidget::showFirstUI(bool b)
{
    m_isFirstUI = b;
    ui->label_wxzf->setVisible(false);
    ui->label_zfbzf->setVisible(false);
    ui->textEdit_whiteList->setVisible(false);
    ui->btn_save->setVisible(false);

    ui->btnReturn->setVisible(!b);
    ui->Btn_Start->setVisible(b);
    if(b) setInfo();

}

void MyWidget::on_btnReturn_clicked()
{
    showFirstUI(true);
}

void MyWidget::label_help_clicked()
{
    QString helpInfo = "\
ClearMap1.11\n\
本软件作为免费产品,因使用本软件而引发的各种问题,软件开发者概不负责.\n\n\
为了安全起见,请在使用本软件前备份你的地图.\n\n\
操作流程:\n\
    1.首次使用请先配置好w2l.exe路径(直接将w3x2lni目录下的w2l.exe拖进来即可).\n\
    2.拖入你的地图,如:xxx.w3x(仅支持obj格式)\n\
    3.点击开始.\n\
更多内容请看使用说明.\n\n\
如果误删了地图中使用了的mdx、blp、tga文件,请与我联系反馈Bug.\n\n\
如果觉得该软件为你带了方便,想打赏作者,可以点击标题栏中的￥按钮.\n\
    作者:冰叶伤痕     Q:124070027\
        ";
    ui->textBrowser->setText(helpInfo);
    showFirstUI(false);
}



void MyWidget::on_btn_whiteList_clicked()
{
    QFileInfo file_info(m_whiteListFile);
    if(file_info.exists()){
        QProcess* process = new QProcess();
        QString notepadPath = QString("notepad.exe %1").arg(m_whiteListFile);
        process->start(notepadPath);
    }
    else
    {
        //创建一个新的默认文件
    }

//    showFirstUI(false);
//    ui->btn_save->setVisible(true);
//    ui->textEdit_whiteList->setVisible(true);
//    QString mdx,pic,dir;
//    for (int i=0;i<m_WhiteListMdxFile.count() ;i++) mdx+=m_WhiteListMdxFile.at(i)+"\n";
//    for (int i=0;i<m_WhiteListPicFile.count() ;i++) pic+=m_WhiteListPicFile.at(i)+"\n";
//    for (int i=0;i<m_WhiteListDir.count() ;i++) dir+=m_WhiteListPicFile.at(i)+"\n";
//    ui->textBrowser->setText("白名单:\n目录:\n"+dir+"模型:\n"+mdx+"\n图片:\n"+pic);


//    QString file_full_path = QFileDialog::getOpenFileName(this,tr("文件对话框"),"F",tr("配置文件(*ini)"));
//    qDebug() <<"file:" <<file_full_path;
}




void MyWidget::on_btn_save_clicked()
{
    //读取模型路径并检测输入贴图数量
    QString mdxPath;
    QString text = ui->textEdit_whiteList->toPlainText();
    QStringList row_list = text.split("\n");
    if(row_list.isEmpty()) {ui->label_info->setText("白名单保存失败!输入数据错误."); return;}

    //检测数据有效性,将\换成/,分类存储
    QStringList temp_WhiteListMdxFile,temp_WhiteListPicFile;
    QRegExp reg_mdx(".*\\.(mdx|mdl)",Qt::CaseInsensitive);
    QRegExp reg_pic(".*\\.(blp|tga)",Qt::CaseInsensitive);
    QRegExp reg_another("\\s*");
    for (int i=0;i<row_list.count() ;i++ )
    {
        QString data = row_list.at(i);
        if(reg_mdx.exactMatch(data))
        {
            temp_WhiteListMdxFile<<data;
            continue;
        }
        if(reg_pic.exactMatch(data))
        {
            temp_WhiteListPicFile<<data;
            continue;
        }
        if(reg_another.exactMatch(data)) continue;

        ui->label_info->setText("白名单保存失败!输入数据错误.");
        return;
    }
    m_WhiteListMdxFile = temp_WhiteListMdxFile;
    m_WhiteListPicFile = temp_WhiteListPicFile;
    ui->label_info->setText("白名单保存成功!");
    QString mdx,pic;
    for (int i=0;i<m_WhiteListMdxFile.count() ;i++) mdx+=m_WhiteListMdxFile.at(i)+"\n";
    for (int i=0;i<m_WhiteListPicFile.count() ;i++) pic+=m_WhiteListPicFile.at(i)+"\n";
    ui->textBrowser->setText("白名单:\n模型:\n"+mdx+"\n图片:\n"+pic);

}

void MyWidget::on_checkBox_readSlk_stateChanged(int arg1)
{
    if(arg1 == 0) m_read_slk = false;   //未选中
    if(arg1 == 2) m_read_slk = true;    //选中
}

void MyWidget::on_checkBox_delLni_stateChanged(int arg1)
{
    if(arg1 == 0) m_del_lni = false;   //未选中
    if(arg1 == 2) m_del_lni = true;    //选中
}
